    let startTime = null;
    let timerInterval = null;
    let elapsedTime = 0;
    document.addEventListener('DOMContentLoaded', function() {
    const baseUrl = '/api/words';
    const categoriesContainer = document.getElementById('categories');
    const wordViewer = document.getElementById('word-viewer');
    const wordsPlaceholder = document.getElementById('words-placeholder');
    const studyControls = document.getElementById('study-controls');
    const quizControls = document.getElementById('quiz-controls');
    const quizContainer = document.getElementById('quiz-container');
    const optionsContainer = document.getElementById('options-container');
    const resultMessage = document.getElementById('result-message');
    const studyModeBtn = document.getElementById('study-mode-btn');
    const quizModeBtn = document.getElementById('quiz-mode-btn');
    const wordModule = document.getElementById('word-module');

    // Word display elements
    const wordEnglish = document.getElementById('word-english');
    const wordCategory = document.getElementById('word-category');
    const wordPos = document.getElementById('word-pos');
    const wordDefinition = document.getElementById('word-definition');
    const wordExample = document.getElementById('word-example');

    // Control buttons
    const showBtn = document.getElementById('show-btn');
    const prevBtn = document.getElementById('prev-btn');
    const nextBtn = document.getElementById('next-btn');
    const nextQuizBtn = document.getElementById('next-quiz-btn');
    const progress = document.getElementById('progress');

    let currentCategoryId = null;
    let words = [];
    let currentIndex = 0;
    let isShowingDefinition = false;
    let currentMode = 'study';
    let currentCorrectAnswer = null;

    // Load all categories
    fetchCategories();

    // Mode selection
    studyModeBtn.addEventListener('click', () => {
    if (currentMode !== 'study') {
    switchMode('study');
}
});

    quizModeBtn.addEventListener('click', () => {
    if (currentMode !== 'quiz') {
    switchMode('quiz');
}
});

    function switchMode(mode) {
    currentMode = mode;

    if (mode === 'study') {
    stopTimer();
    studyModeBtn.classList.add('active');
    quizModeBtn.classList.remove('active');
    studyControls.classList.remove('hidden');
    quizControls.classList.add('hidden');
    quizContainer.classList.add('hidden');
    resultMessage.textContent = '';
    wordModule.classList.remove('quiz-mode');
} else {
    startTimer();
    studyModeBtn.classList.remove('active');
    quizModeBtn.classList.add('active');
    studyControls.classList.add('hidden');
    quizControls.classList.remove('hidden');
    quizContainer.classList.remove('hidden');
    isShowingDefinition = false;
    wordModule.classList.add('quiz-mode');
}

    if (words.length > 0) {
    updateWordDisplay();
}
}
    function startTimer() {
    stopTimer(); // 先停止现有计时器
    startTime = Date.now() - elapsedTime;
    timerInterval = setInterval(updateTimer, 1000);
}

    function stopTimer() {
    clearInterval(timerInterval);
    timerInterval = null;
}

    function resetTimer() {
    stopTimer();
    elapsedTime = 0;
    document.getElementById('timer').textContent = '00:00';
}

    function updateTimer() {
    const currentTime = Date.now();
    elapsedTime = currentTime - startTime;
    const seconds = Math.floor(elapsedTime / 1000);
    const minutes = Math.floor(seconds / 60);
    const displaySeconds = seconds % 60;

    document.getElementById('timer').textContent =
    `${minutes.toString().padStart(2, '0')}:${displaySeconds.toString().padStart(2, '0')}`;
}
    function fetchCategories() {
    fetch(`${baseUrl}/categories`)
    .then(response => {
    if (!response.ok) {
    throw new Error('网络请求失败');
}
    return response.json();
})
    .then(categories => {
    displayCategories(categories);
})
    .catch(error => {
    categoriesContainer.innerHTML = `<div class="error">加载分类失败: ${error.message}</div>`;
    console.error('加载分类错误:', error);
});
}
// 复习错词按钮点击事件
    document.getElementById('review-mistakes-btn').addEventListener('click', () => {
    document.querySelectorAll('.category-btn').forEach(btn => {
    btn.classList.remove('active');
});
    document.getElementById('review-mistakes-btn').classList.add('active');

    fetchMistakeWords();
});

    function fetchMistakeWords() {
    resetTimer();
    wordsPlaceholder.textContent = '加载错词中...';
    wordViewer.classList.add('hidden');
    currentCategoryName = '错词复习';

    const userId = getUserId();
    if (!userId) {
    wordsPlaceholder.innerHTML = '<div class="error">请先登录</div>';
    return;
}

    fetch(`${baseUrl}/mistake-words`)
    .then(response => {
    if (!response.ok) {
    throw new Error('网络请求失败');
}
    return response.json();
})
    .then(loadedWords => {
    if (!loadedWords || loadedWords.length === 0) {
    wordsPlaceholder.innerHTML = '<div class="error">没有需要复习的错词</div>';
    return;
}

    words = loadedWords;
    currentIndex = 0;
    isShowingDefinition = false;
    startWordViewer();
})
    .catch(error => {
    wordsPlaceholder.innerHTML = `<div class="error">加载错词失败: ${error.message}</div>`;
    console.error('加载错词错误:', error);
});
}
    function displayCategories(categories) {
    if (categories.length === 0) {
    categoriesContainer.innerHTML = '<div class="error">没有找到分类</div>';
    return;
}

    categoriesContainer.innerHTML = '';
    categories.forEach(category => {
    const button = document.createElement('button');
    button.className = 'category-btn';
    button.textContent = category.name || `分类 ${category.id}`;
    button.dataset.id = category.id;

    button.addEventListener('click', () => {
    document.querySelectorAll('.category-btn').forEach(btn => {
    btn.classList.remove('active');
});
    button.classList.add('active');

    currentCategoryId = category.id;
    fetchWordsByCategory(category.id);
});

    categoriesContainer.appendChild(button);
});
}

    function fetchWordsByCategory(categoryId) {
    resetTimer();
    wordsPlaceholder.textContent = '加载单词中...';
    wordViewer.classList.add('hidden');

    const activeCategoryBtn = document.querySelector('.category-btn.active');
    currentCategoryName = activeCategoryBtn ? activeCategoryBtn.textContent : '未知分类';
    fetch(`${baseUrl}/category/${categoryId}`)
    .then(response => {
    if (!response.ok) {
    throw new Error('网络请求失败');
}
    return response.json();
})
    .then(loadedWords => {
    if (!loadedWords || loadedWords.length === 0) {
    wordsPlaceholder.innerHTML = '<div class="error">该分类中没有单词</div>';
    return;
}

    words = loadedWords;
    currentIndex = 0;
    isShowingDefinition = false;
    startWordViewer();
})
    .catch(error => {
    wordsPlaceholder.innerHTML = `<div class="error">加载单词失败: ${error.message}</div>`;
    console.error('加载单词错误:', error);
});
}

    function startWordViewer() {
    wordsPlaceholder.classList.add('hidden');
    wordViewer.classList.remove('hidden');
    updateWordDisplay();
}

    function updateWordDisplay() {
    const currentWord = words[currentIndex];

    wordEnglish.textContent = currentWord.english || '未知单词';
    wordCategory.textContent = currentCategoryName || '未知分类';
    wordPos.classList.add('hidden');
    wordDefinition.classList.add('hidden');
    wordExample.classList.add('hidden');
    resultMessage.textContent = '';
    optionsContainer.innerHTML = '';

    if (currentWord.exampleSentence) {
    wordExample.textContent = `例句: ${currentWord.exampleSentence}`;
    wordExample.classList.remove('hidden');
}
    if (currentMode === 'study') {
    if (isShowingDefinition) {
    if (currentWord.partOfSpeech) {
    wordPos.textContent = `[${currentWord.partOfSpeech}]`;
    wordPos.classList.remove('hidden');
}

    wordDefinition.textContent = currentWord.chinese || '暂无释义';
    wordDefinition.classList.remove('hidden');

    if (currentWord.exampleSentence) {
    wordExample.textContent = `例句: ${currentWord.exampleSentence}`;
    wordExample.classList.remove('hidden');
}

    showBtn.textContent = '隐藏释义';
} else {
    showBtn.textContent = '显示释义';
}
} else {
    showBtn.textContent = '显示释义';
    generateQuizOptions(currentWord);
}

    progress.textContent = `${currentIndex + 1}/${words.length}`;

    prevBtn.disabled = currentIndex === 0;
    nextBtn.disabled = currentIndex === words.length - 1;
    nextQuizBtn.disabled = true;
}

    function generateQuizOptions(currentWord) {
    const options = [currentWord.chinese];
    const otherWords = words.filter(w => w.id !== currentWord.id);

    const shuffled = [...otherWords].sort(() => 0.5 - Math.random());
    const wrongOptions = shuffled.slice(0, 3).map(w => w.chinese);

    options.push(...wrongOptions);
    const shuffledOptions = options.sort(() => 0.5 - Math.random());
    currentCorrectAnswer = currentWord.chinese;

    optionsContainer.innerHTML = '';
    shuffledOptions.forEach(option => {
    const button = document.createElement('button');
    button.className = 'option-btn';
    button.textContent = option;
    button.addEventListener('click', () => checkAnswer(option, button));
    optionsContainer.appendChild(button);
});
}

    function checkAnswer(selectedAnswer, button) {
    if (selectedAnswer === currentCorrectAnswer) {
    button.classList.add('correct');
    resultMessage.textContent = '正确!';
    resultMessage.className = 'result-message correct-message';
    nextQuizBtn.disabled = false;

    document.querySelectorAll('.option-btn').forEach(btn => {
    btn.disabled = true;
    if (btn.textContent === currentCorrectAnswer) {
    btn.classList.add('correct');
}
});
} else {
    button.classList.add('incorrect');
    resultMessage.textContent = '错误! 正确答案是: ' + currentCorrectAnswer;
    resultMessage.className = 'result-message incorrect-message';
    nextQuizBtn.disabled = false;

    document.querySelectorAll('.option-btn').forEach(btn => {
    btn.disabled = true;
    if (btn.textContent === currentCorrectAnswer) {
    btn.classList.add('correct');
}
});

    recordMistake(words[currentIndex].id);
}
}

    function recordMistake(wordId) {
    const userId = getUserId();

    fetch(`${baseUrl}/record-mistake`, {
    method: 'POST',
    headers: {
    'Content-Type': 'application/json',
},
    body: JSON.stringify({
    userId: userId,
    wordId: wordId
})
})
    .then(response => {
    if (!response.ok) {
    throw new Error('记录错误失败');
}
    return response.json();
})
    .then(data => {
    console.log('错误已记录:', data);
})
    .catch(error => {
    console.error('记录错误时出错:', error);
});
}

    showBtn.addEventListener('click', () => {
    if (currentMode === 'study') {
    isShowingDefinition = !isShowingDefinition;
    updateWordDisplay();
} else {
    wordDefinition.textContent = words[currentIndex].chinese || '暂无释义';
    wordDefinition.classList.remove('hidden');
}
});

    prevBtn.addEventListener('click', () => {
    if (currentIndex > 0) {
    currentIndex--;
    isShowingDefinition = false;
    updateWordDisplay();
}
});

    nextBtn.addEventListener('click', () => {
    if (currentIndex < words.length - 1) {
    currentIndex++;
    isShowingDefinition = false;
    updateWordDisplay();
}
});

    nextQuizBtn.addEventListener('click', () => {
    if (currentIndex < words.length - 1) {
    currentIndex++;
    isShowingDefinition = false;
    updateWordDisplay();
} else {
    stopTimer();
    wordViewer.classList.add('hidden');
    wordsPlaceholder.classList.remove('hidden');
    wordsPlaceholder.innerHTML = `
            <div class="correct-message">
                测试完成!<br>
                用时: ${document.getElementById('timer').textContent}
            </div>`;
    resetTimer(); // 重置计时器
}
});

    document.addEventListener('keydown', (e) => {
    if (!wordViewer.classList.contains('hidden')) {
    switch(e.key) {
    case 'ArrowLeft':
    if (currentMode === 'study' && currentIndex > 0) {
    currentIndex--;
    isShowingDefinition = false;
    updateWordDisplay();
}
    break;
    case 'ArrowRight':
    if (currentMode === 'study' && currentIndex < words.length - 1) {
    currentIndex++;
    isShowingDefinition = false;
    updateWordDisplay();
}
    break;
    case ' ':
    case 'Enter':
    if (currentMode === 'study') {
    isShowingDefinition = !isShowingDefinition;
    updateWordDisplay();
}
    break;
}
}
});
});

    function getUserId() {
    return document.getElementById('userId').value;
}
